﻿using Common.Library;
using PicasaMobileInterface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace Social_Celebrities
{
   public class UpdateRatingInBlog
    {
        public AutoResetEvent auto = new AutoResetEvent(false);

        public Dictionary<string, object> dictionary = new Dictionary<string, object>();

        public void Login(string username, string password,string Type)
        {
            BloggerInterface BI = new BloggerInterface(username, password, Type);
        }

        public void UploadItem(AutoResetEvent Auto, Dictionary<string, object> dic)
        {
            try
            {
                auto = Auto;
                dictionary = dic;
                string ID = dic.Where(i => i.Key == "PostID").FirstOrDefault().Value.ToString();
                string BlogID = ID.Substring(ID.IndexOf('-') + 1, (ID.LastIndexOf('.') - (ID.IndexOf('-') + 1)));
                string PostID = ID.Substring(ID.LastIndexOf('-') + 1);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.blogger.com/feeds/"+BlogID+"/posts/default/"+PostID);
                request.Method = "PUT";
                request.ContentType = "application/atom+xml";
                request.Headers["Authorization"] = CONST.PIC_AUTH + AppSettings.BloggerAccessTokenForRating;
                request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackItem), request);
            }
            catch
            {
               
                auto.Set();
            }
        }
        private void GetRequestStreamCallbackItem(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest webrequest = (HttpWebRequest)asynchronousResult.AsyncState;
                BlogData(asynchronousResult, webrequest);
            }
            catch
            {
                
                auto.Set();
            }
        }


        private void BlogData(IAsyncResult asynchronousResult, HttpWebRequest request, string datacustom = "")
        {
            try
            {
                Stream postStream = new MemoryStream();
                string contentformat = "<div style='float: left;'><table><tr><td><div style='float: top;'><img  src='" + dictionary.Where(i => i.Key == "Image").FirstOrDefault().Value + "' width='200px' height='200px'/></div></td><td><p>" + dictionary.Where(i => i.Key == "Title").FirstOrDefault().Value + "</p></td></tr></table>" + "<div style='display: none;' xmlns='http://www.w3.org/1999/xhtml'>" +
                         "<![CDATA[" + "??" + dictionary.Where(i => i.Key == "XML").FirstOrDefault().Value + "]]>" +
                           "</div></div>";
                string contents = "<entry xmlns='http://www.w3.org/2005/Atom'>" +
                          "<title type='text'>" + dictionary.Where(i => i.Key == "Title").FirstOrDefault().Value + "</title>" +
                          "<category scheme='http://www.blogger.com/atom/ns#' term='" + dictionary.Where(i => i.Key == "Title").FirstOrDefault().Value + "'/>" +
                          "<category scheme='http://www.blogger.com/atom/ns#' term='" + Convert.ToInt32(dictionary.Where(i => i.Key == "Rating").FirstOrDefault().Value).ToString() + "'/>" +
                          "<content type='xhtml'>" +
                            contentformat +
                          "</content>" +
                          "</entry>";

                Stream ms = new MemoryStream(Encoding.UTF8.GetBytes(contents));
                postStream = request.EndGetRequestStream(asynchronousResult);
                byte[] buffer = new byte[ms.Length / 4];
                int bytesRead = -1;
                ms.Position = 0;
                while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) > 0)
                {
                    postStream.Write(buffer, 0, bytesRead);
                }
                ms.Flush();
                ms.Close();
                postStream.Flush();
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(RequestAlbumCompletedItem), request);
            }
            catch
            {
               
                auto.Set();
            }
        }

        private void RequestAlbumCompletedItem(IAsyncResult result)
        {
            try
            {
                var request = (HttpWebRequest)result.AsyncState;
                var response = (HttpWebResponse)request.EndGetResponse(result);
                StreamReader responseReader = new StreamReader(response.GetResponseStream());
                string responseStr = responseReader.ReadToEnd();
             
                auto.Set();
            }
            catch
            {
               
                auto.Set();
            }
        }
    }
}
